package com.naldo.goodcard.SQL;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DbAdapter {
	
	private SQLiteDatabase database;
	private DbHelper dbHelper;
	private String[] allColumns = { DbHelper.ID, 
									DbHelper.TIPO, 
									DbHelper.NUMERO,
									DbHelper.CPF };
	
	public DbAdapter(Context context) {          
		this.dbHelper = new DbHelper(context);
		this.database = dbHelper.getWritableDatabase();
	}
	
	public Cartao createCartao(String tipo, String numero, String cpf) {
		
        ContentValues values = new ContentValues(); 
        values.put(dbHelper.TIPO, tipo); 
        values.put(dbHelper.NUMERO, numero);
        values.put(dbHelper.CPF, cpf); 
        
        long insertId = database.insert(dbHelper.TABLE_NAME, null, values); 
       
        // To show how to query 
       Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + 
       insertId, null,null, null, null); 
       
       cursor.moveToFirst(); 
       
       return cursorToCartao(cursor); 
	}
	
	
	public Cartao createCartao(Cartao cartao) {
		ContentValues values = new ContentValues(); 
		values.put(dbHelper.TIPO, cartao.getTipo()); 
		values.put(dbHelper.NUMERO, cartao.getNumero());
		values.put(dbHelper.CPF, cartao.getCPF()); 
		
		long insertId=0;
		
		insertId = database.insert(dbHelper.TABLE_NAME, null, values); 
		
		// To show how to query 
		Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + 
		insertId, null,null, null, null); 
		   
		cursor.moveToFirst(); 
		
		return cursorToCartao(cursor); 
	}
	
	
	public void ExcluirCartao (long idCartao){ 
        database.delete(DbHelper.TABLE_NAME, DbHelper.ID + " = " + idCartao, 
         null); 
	}	
	
	private Cartao cursorToCartao(Cursor cursor) {
        Cartao cartao = new
		Cartao(cursor.getLong(0),cursor.getString(1),cursor.getString(2), 
        cursor.getString(3));
        
        return cartao; 
	}
		
	public Cartao getCartao(long id) {

		// To show how to query 
		Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + 
				id, null,null, null, null); 
		   
		cursor.moveToFirst(); 
		
		return cursorToCartao(cursor); 
	}
	
	public List<Cartao> selectAll() {
	      List<Cartao> list = new ArrayList<Cartao>();
	      Cursor cursor = this.database.query(DbHelper.TABLE_NAME, allColumns,
	        null, null, null, null, "_id desc");
	      if (cursor.moveToFirst()) {
	         do {
	        	list.add(cursorToCartao(cursor));	            
	         } while (cursor.moveToNext());
	      }
	      if (cursor != null && !cursor.isClosed()) {
	         cursor.close();
	      }
	      return list;
	   }
	
}
